package xyz.zhzby.cyzx.oj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.ApiOperation;
import xyz.zhzby.cyzx.oj.entity.ProblemCategory;
import xyz.zhzby.cyzx.oj.mapper.ProblemCategoryMapper;
import xyz.zhzby.cyzx.oj.service.IProblemCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.zhzby.cyzx.security.entity.User;
import xyz.zhzby.cyzx.security.util.CyzxSecurityContextHolder;
import xyz.zhzby.cyzx.servicebase.domain.DataLogInfo;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 试题与试题分类关联表 服务实现类
 * </p>
 *
 * @author zby
 * @since 2021-12-26
 */
@Service
public class ProblemCategoryServiceImpl extends ServiceImpl<ProblemCategoryMapper, ProblemCategory> implements IProblemCategoryService {

    @Override
    public void linkProblemCategory(Long id, List<Long> categoryIds) {
        removeByProblemId(id);

        User subject = CyzxSecurityContextHolder.getSubject();
        for (Long categoryId : categoryIds) {
            ProblemCategory problemCategory = new ProblemCategory();
            problemCategory.setProblemId(id);
            problemCategory.setCategoryId(categoryId);
            subject.fillCreateInfo(problemCategory, DataLogInfo.USER_FIELD_ACTUAL_NAME);
            baseMapper.insert(problemCategory);
        }
    }

    @ApiOperation("根据试题ID删除关联")
    private void removeByProblemId(Long problemId) {
        LambdaQueryWrapper<ProblemCategory> qw = new LambdaQueryWrapper<>();
        qw.eq(ProblemCategory::getProblemId, problemId);
        baseMapper.delete(qw);
    }

    @Override
    public List<Long> getProblemIdsByCategoryId(Long categoryID) {
        LambdaQueryWrapper<ProblemCategory> qw = new LambdaQueryWrapper<>();
        qw.eq(ProblemCategory::getCategoryId, categoryID);
        qw.select(ProblemCategory::getProblemId);
        List<ProblemCategory> problemCategories = baseMapper.selectList(qw);
        return problemCategories.stream().map(ProblemCategory::getProblemId).collect(Collectors.toList());
    }
}
